Repository navigation
Fix orphaned Laminar traces from cross-async-context conversations - #3113
Conversation
Production traces show ~63% of conversations end up split across multiple
top-level Laminar traces: 327/520 traces in a 24h sample have
top_span_name in {conversation.send_message, conversation.run,
litellm.completion} with parent_span_id=00000000…, and 100% of those
orphans have empty session_id.
Root cause: the SDK starts the conversation root span via
Laminar.start_active_span in BaseConversation.__init__ and stores it in
a process-global SpanManager LIFO stack. start_active_span attaches the
OTel context using contextvars, which only propagates to tasks created
*after* the attach, on the *same* thread. When send_message / run /
generate_title are invoked from a different asyncio task or thread
(e.g. FastAPI handlers, websocket loops, RemoteConversation callers),
the @observe-decorated method does not see the conversation as its
parent and starts a fresh root trace. The Laminar SDK explicitly warns
against this pattern and recommends start_span + use_span instead.
A second, related bug: the global LIFO SpanManager corrupts state when
multiple Conversations are alive concurrently — closing one pops
whichever span happens to be on top.
Fix:
- Replace the global SpanManager with a per-conversation RootSpan owned
by BaseConversation as self._observability_root_span.
- Create the root via Laminar.start_span (no implicit context attach).
- Have the @observe wrapper inspect the first positional arg for an
_observability_root_span attribute and re-attach it via
Laminar.use_span at every entry point. Nested @observe and lmnr
auto-instrumented spans automatically inherit the right parent.
- Apply session_id by briefly entering use_span at construction time so
it lands on the trace metadata.
- Keep SpanManager / start_active_span / end_active_span as deprecated
shims for backwards compatibility.
Add three regression tests:
- sync entry points re-attach the owner's root span;
- async entry points re-attach the owner's root span even when invoked
from a freshly-created asyncio.Task with an empty contextvars.Context;
- two concurrent conversations get independent root spans and ending
one does not affect the other.
Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
The previous tests patched start_active_span / end_active_span on the base module; those names are still exported (as deprecated shims) but BaseConversation now calls start_root_span / end_root_span. Update the patches and assertions to target the new function names, and add an idempotency assertion: a second _start_observability_span on an already-started conversation must not start a second root span. Co-authored-by: openhands <openhands@all-hands.dev>
|
✅ Full SDK test suite: 3573 passed, 0 failed ( Two tests deselected are pre-existing environmental failures, both confirmed independent of this PR by reproducing them on
Includes a follow-up commit (a76818d) that updates — OpenHands |
- Drop now-unused TYPE_CHECKING import of opentelemetry.trace from observability/laminar.py (referenced only by the old SpanManager). - Reorder imports in the new regression tests to satisfy ruff isort. Co-authored-by: openhands <openhands@all-hands.dev>
…n shims
Audit on 2026-05-07 found *zero* callers of these symbols outside the SDK
itself:
- 0 hits in OpenHands/OpenHands (grep + GitHub code search)
- 0 hits in OpenHands/agent-canvas (TypeScript-only)
- 0 hits in OpenHands/codescout (only ``maybe_init_laminar`` is imported)
- 0 hits elsewhere in the OpenHands org via GitHub code search
The shims are kept solely to protect any unaudited private/external
consumer. To make the schedule explicit, every shim now calls
``warn_deprecated`` with:
deprecated_in="1.22.0" # this PR ships in 1.22.0
removed_in="1.27.0" # 5-minor-version grace window matches the
# SDK's existing precedent for
# VerificationSettings.confirmation_mode
# (deprecated 1.17.0, removed 1.22.0)
The warning is silent during 1.21.x development and activates the moment
1.22.0 ships. ``_get_span_manager`` was tweaked to construct the legacy
``SpanManager`` via ``__new__`` so wiring up the singleton doesn't itself
emit a deprecation warning.
Adds ``test_deprecated_shims_emit_warnings`` which patches
``_current_version`` to 1.22.0 and asserts each shim emits the expected
``DeprecationWarning``.
Co-authored-by: openhands <openhands@all-hands.dev>
Deprecation schedule + downstream-consumer auditTo answer the question of how long to keep the backwards-compat shims ( Audit results (2026-05-07):
So in practice no first- or second-party caller uses the deprecated symbols. The shims now exist purely to give any unaudited private consumer a heads-up before the SDK simply removes them. Schedule (matches existing SDK precedent): This matches the SDK's previous
Re transitioning OpenHands/OpenHands or agent-canvas: nothing to transition. Both repos are clean. The only transition needed was inside this SDK itself, which the rest of this PR already handles ( Added — OpenHands |
…s.py The repo's .github/scripts/check_deprecations.py walks the AST and only accepts string literals (or date.today()) for deprecated_in / removed_in. The previous commit factored these out to module-level Final[str] constants which the scanner rejects as "Unsupported removed_in expression". Inline the literal strings to satisfy the scanner — the human-readable schedule comment at the top of the shim block still documents the policy. Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 Good taste - Elegant solution that eliminates the root cause
Excellent problem analysis and fix. The switch from a global LIFO stack (SpanManager) to per-conversation owned RootSpan objects is exactly the right data structure choice — it eliminates both the cross-async-context bug and the concurrent-conversation collision bug at once.
The @observe decorator change is minimal and clean: re-attach the owner's root span at every entry point via Laminar.use_span, which is the pattern Laminar explicitly recommends in their docs. The three regression tests directly target the bugs and prove the fix works, including the isolated-context scenario that reproduced the 63% orphan rate.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟢 LOW
This changes internal observability instrumentation only. The fix makes traces more correct (child spans properly nested under conversation root) without affecting agent behavior, tool execution, or benchmark performance. Backward-compatible shims preserve the old API with proper deprecation warnings (1.22.0 → 1.27.0, following the 5-minor-version policy). The new pattern is upstream-recommended and the old global stack had no external callers per the org-wide audit.
VERDICT:
✅ Worth merging - Solves a real production problem (63% orphan traces) with a clean, well-tested fix.
KEY INSIGHT:
Per-object span ownership + entry-point re-attachment via use_span is the correct pattern for trace propagation across async/thread boundaries where contextvars breaks down.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The PR successfully fixes orphaned Laminar traces by ensuring child spans correctly attach to the conversation root span across async contexts.
Does this PR achieve its stated goal?
Yes. The PR fixes the orphan trace bug where ~63% of conversations showed up as split traces in Laminar. The fix ensures that all child spans (conversation.send_message, conversation.run, agent.step, tool calls) correctly nest under the conversation root span with proper session_id propagation, regardless of which async task or thread invokes the methods. This addresses the root cause (contextvars failing to propagate across async boundaries) by switching to the upstream-recommended start_span + use_span pattern.
| Phase | Result |
|---|---|
| Environment Setup | ✅ Built successfully via make build |
| CI Status | ✅ 30 checks passing, 0 failing |
| Functional Verification | ✅ All behaviors verified |
Functional Verification
Test 1: Unit tests verify the fix
Ran the observability test suite:
python -m pytest tests/sdk/observability/test_laminar.py -vResult: All 29 tests passed, including the 3 new regression tests:
test_observe_calls_use_span_with_owner_root_span_on_sync✅test_observe_calls_use_span_with_owner_root_span_on_async✅ (the key cross-context bug scenario)test_two_concurrent_conversations_do_not_collide✅test_deprecated_shims_emit_warnings✅
Interpretation: The tests prove that:
- The
@observedecorator callsLaminar.use_span()with the owner's root span at every entry point - This works even when methods are called from isolated async contexts (the bug scenario)
- Concurrent conversations get independent root spans (no global stack collision)
- Deprecated APIs still work and emit proper warnings
Test 2: Cross-context span propagation demonstration
Created a demonstration script that:
- Creates a conversation with a root span
- Calls
@observe-decorated methods from the same async context - Calls
@observe-decorated methods from a fresh, isolated async context (simulating the bug) - Tracks all
Laminar.use_span()calls via mocking
Result: use_span() was called with the correct root span in ALL cases, including when invoked from an isolated context with no parent contextvars.
Interpretation: This proves the fix works. Before the fix, calling a conversation method from a different async task (e.g., RemoteConversation handling a websocket message) would start a fresh root trace because contextvars don't propagate to pre-existing tasks. After the fix, the root span is stored on the conversation object and explicitly re-attached at every entry point, so cross-context calls work correctly.
Test 3: Concurrent conversations don't collide
Created two concurrent conversation objects and verified:
- Each gets its own independent root span
- Ending conversation 2's span doesn't affect conversation 1
- Each span ends independently
Result: Both conversations maintained independent root spans throughout their lifecycle.
Interpretation: This proves the global SpanManager LIFO stack bug is fixed. Before the fix, two concurrent conversations would push/pop from a shared stack, causing the second conversation to corrupt the first's span on close. After the fix, each conversation owns its root span, so they can coexist safely.
Test 4: Backward compatibility maintained
Tested the deprecated start_active_span() and end_active_span() APIs:
Result: Both deprecated functions still work and emit proper DeprecationWarning messages indicating:
deprecated_in="1.22.0"removed_in="1.27.0"- Clear migration guidance to
start_root_span()/end_root_span()
Interpretation: External users who may have imported these APIs (though the PR description notes an org-wide audit found zero external usages) get a 5-minor-version grace period to migrate, with clear warnings and migration instructions.
Issues Found
None.
Verdict: This PR delivers exactly what it promises. The orphan trace bug is fixed via the correct architectural approach (per-conversation root span ownership + explicit re-attachment), the fix is comprehensively tested, backward compatibility is maintained, and CI is green. Ready to merge.
…penHands#3113) Co-authored-by: openhands <openhands@all-hands.dev>
…penHands#3113) Co-authored-by: openhands <openhands@all-hands.dev>
Problem
While auditing trace ingestion at
https://laminar.app.all-hands.dev/, ~63% of conversations show up as orphaned/split traces.In a 24h window (520 traces, last 14d):
conversation(root) ✅conversation.send_messageconversation.runtools/call create_prlitellm.completionThe orphan spans have
parent_span_id = 00000000-0000-0000-0000-000000000000and contain real LLM/tool data — i.e. successful agent runs are being torn into 2-3 unrelated traces in the dashboard, with nosession_idto stitch them back together.Root cause
BaseConversation._start_observability_spancallsLaminar.start_active_span("conversation"), which attaches the OTel context usingcontextvars.attach(). From the upstream Laminar docstring (verbatim):contextvarsonly propagate to tasks created after the attach, on the same thread. Pre-existing async tasks (FastAPI handlers, websocket loops, anythingRemoteConversationdoes) don't see the parent. When such a task calls a method decorated with@observe(...)—send_message,run,generate_title,agent.step,MCPToolExecutor.call_tool— it starts a fresh root trace and the conversation is silently torn apart.A second related bug:
SpanManageris a process-wide LIFO stack. Two concurrentConversationinstances corrupt each other — closing one pops whichever span happens to be on top.Fix
Switch to the upstream-recommended
start_span+use_spanpattern:RootSpanowned by the conversation.BaseConversationstores its root span onself._observability_root_spaninstead of pushing onto a global stack.start_root_spanusesLaminar.start_span(no implicit context attach).session_idis applied via a briefuse_spanwindow so it lands on trace metadata.@observere-attaches the root span at every entry point. The decorator wrapper inspects the first positional arg (self) for an_observability_root_span, and if present wraps the call inLaminar.use_span(...). Nested@observe'd calls and lmnr's auto-instrumentation inherit the right parent automatically.SpanManager,start_active_span,end_active_spanare now thin wrappers around the new primitive, so anything outside the SDK that imported them still works (just without the global-collision footgun).Effect on the trace shape
Before:
After:
Tests
Three new regression tests in
tests/sdk/observability/test_laminar.py:test_observe_calls_use_span_with_owner_root_span_on_sync— sync@observe'd methods re-attach the owner's root span viaLaminar.use_span.test_observe_calls_use_span_with_owner_root_span_on_async— async@observe'd methods re-attach even when invoked from a freshly-createdasyncio.Taskwith an emptycontextvars.Context(the cross-context bug repro).test_two_concurrent_conversations_do_not_collide— twoConversationinstances get independent root spans and ending one does not affect the other.All 28 observability tests pass locally; full SDK suite is running and I'll update this PR with the result before un-drafting.
Risk assessment
RootSpan/start_root_span/end_root_span.start_active_span/end_active_span/SpanManagerare kept as functionally-equivalent shims.observewrapper now does onegetattrand (when observability is enabled and the owner has a root span) aLaminar.use_spanper call. That's roughly the same workstart_active_spanwas doing internally; it's just moved to the call site so it works across async/thread boundaries. Negligible perf impact.use_spanis logged at debug and the wrapped function is still called, so observability errors can never break the SDK.Why this is structural, not transient
The 63% orphan rate is determined by how callers use the SDK, not by data freshness. Every caller that constructs a
Conversationin one task and invokessend_message/runfrom a different task hits this —RemoteConversationis one such caller by design. Waiting longer in production won't reduce the orphan rate.Marking as draft for review — happy to iterate on naming or scope.
This PR was opened by an AI agent (OpenHands) on behalf of @neubig.
@neubig can click here to continue refining the PR
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:1253592-pythonRun
All tags pushed for this build
About Multi-Architecture Support
1253592-python) is a multi-arch manifest supporting both amd64 and arm641253592-python-amd64) are also available if needed